/*
 ============================================================================
 Name        : server_applicatie.c
 Author      : 
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#include "server_applicatie.h"

char *sensorBuffer;

/**
 * Continuously generates sensor values
 */
void sensorReadLoop() {
	int i = 0;

	while (1) {
		for (i = 0; i < 10; i++) {
			read10msSensorValues();
			check10msSensorsForAlarms();
			Sleep(10);
		}
		read100msSensorValues();
		check100msSensorsForAlarms();
	}
}

DWORD WINAPI SensorSendThread() {
	int size;
	while (1) {
		Sleep(SENSOR_SEND_INTERVAL);
		size = sensorsToJson(analogSensors10ms, ANALOG_SENSORS_10MS_AMOUNT,
				analogSensors100ms, ANALOG_SENSORS_100MS_AMOUNT, binarySensors,
				BINARY_SENSORS_AMOUNT, sensorBuffer);
		printf("JSON created, size = %d\n", size);
		putInSendBuffers(sensorBuffer, size);
	}
}

int startThreads() {
	HANDLE thread = CreateThread(NULL, 0, CommThread, NULL, 0, NULL );
	if (thread == 0) {
		puts("Comm thread creation failed");
		return 1;
	}
	thread = CreateThread(NULL, 0, SensorSendThread, NULL, 0, NULL );
	if (thread == 0) {
		puts("Sensor send thread creation failed");
		return 1;
	}
	sensorReadLoop();
}

int main(void) {
	printf("Amount of sensors: %d, using buffer size %d\n",
			SENSORS_TOTAL_AMOUNT, SEND_BUFFER_SIZE);
	sensorBuffer = malloc(SEND_BUFFER_SIZE);

	initSensors();
	initClientSlots();
	startThreads();

//	testJsonParsing();

	return 0;
}
